﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BYUStock
{
    public  static class DbHelper
    {
        public  static string ConnStr = "Data Source =" + AppDomain.CurrentDomain.BaseDirectory + "stock_base.db;";
        public static bool InsertBk(string id, string name, string kind, int total, string date)
        {
            using (var conn = new SQLiteConnection(ConnStr))
            {
                conn.Open();
                var sql = $@"insert into GroupKind values({id},{name},{kind},{total},{date});";
                using (var cmd = new SQLiteCommand(sql))
                {
                    cmd.Connection = conn;
                    return cmd.ExecuteNonQuery() == 1;
                }
            }
        }

        public static bool SyncStocksFromBks()
        {
            int syncFails = 0;
            using (var conn = new SQLiteConnection(ConnStr))
            {
                conn.Open();
                var sql = "select DISTINCT Code,StockName from StockGroup where Code in (select DISTINCT Code from StockGroup);";
                using (var cmd = new SQLiteCommand(sql))
                {
                    cmd.Connection = conn;
                    var reader = cmd.ExecuteReader();
                    var date = Global.GetDate();
                    while (reader.Read())
                    {
                        var stockCode = reader.GetString(0);
                        var stockName = reader.GetString(1);
                        var sqlexsit = $"select Code from StockBaseInfo where Code = '{stockCode}';";
                        using (var cmd2 = new SQLiteCommand(sqlexsit))
                        {
                            cmd2.Connection = conn;
                            cmd2.CommandText = sqlexsit;
                            if (cmd2.ExecuteScalar() == null)
                            {
                                var sqlInsert = $"insert into StockBaseInfo values('{stockCode}','{stockName}','BYU','{2}','{date}','{date}');";
                                cmd2.CommandText = sqlInsert;
                                var result = cmd2.ExecuteNonQuery();
                                if (result != 1)
                                {
                                    syncFails++;
                                }
                            }
                        }
                    }
                }
            }
            return syncFails == 0;
        }

    }
}
